from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SPU, Brand, GoodsCategory
from apps.meiduo_admin.utils import PageNum
from ..serializers.spu import SpuListModelSerializer, BrandInfoModelSerializer, CategoryInfoModelSerializer
from rest_framework.generics import ListAPIView


class SpuListView(ModelViewSet):

    # queryset = SPU.objects.all() 重写获取到的查询集数据
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return SPU.objects.filter(name__contains=keyword)
        return SPU.objects.all()
    serializer_class = SpuListModelSerializer
    pagination_class = PageNum


# 获取品牌信息
class BrandInfoView(APIView):
    def get(self, request):
        instances = Brand.objects.all()
        serializer = BrandInfoModelSerializer(instance=instances, many=True)
        return Response(serializer.data)


# 获取一级品类视图
class CategoryInfoView(ListAPIView):

    # queryset = GoodsCategory.objects.filter(parent=None) 重写，针对不同的分类级别查询不同的查询集
    def get_queryset(self):
        pk = self.kwargs.get('pk')
        if pk:
            return GoodsCategory.objects.filter(parent=pk)
        return GoodsCategory.objects.filter(parent=None)
    serializer_class = CategoryInfoModelSerializer